﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using infoMngmntGUI.View;
using infoMngmntGUI.Control;
using System.Data;

namespace infoMngmntGUI.View
{
    /// <summary>
    /// Interaction logic for Search_Patient.xaml
    /// </summary>
    public partial class Search_Patient : IView
    {
        public Search_Patient()
        {
            minimumAccess = Control.AccessManagement.UserType.NURSE;
            InitializeComponent();
        }

        public override string ToString()
        {
            return "Search For Patient";
        }

        /*
         * Simple event handler to quickly clear all the field text boxes including the results from the 
         * last query received.
         */
        private void cancelButton_Click(object sender, RoutedEventArgs e)
        {
            //resultsTextBox.Text = "Sample Query Output";
            firstNameTextBox.Text = "";
            lastNameTextBox.Text = "";
            dobDatePicker.Text = "";

            firstNameTextBox.IsEnabled = true;
        }

        /*
         * Event handler for performing a patient query.  Checks for a valid input first, if valid, extracts 
         * the search criteria from the fields, if the list is not empty, then the criteria attribute list is 
         * passed to the DbConnection to perform the query.  The DbConnection queries the database and returns 
         * a list of results from said query.  Each record in the result list is added to the result text box 
         * on the page to be displayed.  
         */
        private void searchButton_Click(object sender, RoutedEventArgs e)
        {
            if (IsValidInput())
            {
                //resultsTextBox.Text = "Sample Query Output";

                List<string> criteria;
                if ((criteria = GetSearchCriteria()).Count != 0)
                {
                    //resultsTextBox.Text += "\n\n";
                    //List<string> results = DbConnection.SearchPatients(criteria);

                    dataGrid.HorizontalScrollBarVisibility = ScrollBarVisibility.Visible;
                    dataGrid.VerticalScrollBarVisibility = ScrollBarVisibility.Visible;
                    dataGrid.AutoGenerateColumns = true;

                    DataSet dataSet = new DataSet("Query Data Set");
                    DataTable queryResults = DbConnection.SearchPatients(criteria);
                    dataSet.Tables.Add(queryResults);
                    dataGrid.ItemsSource = dataSet.Tables[0].DefaultView;

                }
            }
        }

        /*
         * Checks to see which fields were used by the user to perform a query.  Validates to make sure that the 
         * necessary search criteria are present (did not just enter first name by itself, for example).  If the 
         * criteria allow for a valid query, then the data is extracted from the text boxes, added to a list of 
         * attribute strings, and passed to the DbConnection class to perform the query.
         */
        private List<string> GetSearchCriteria()
        {
            List<string> criteria = new List<string>();

            if (dobDatePicker.Text == "")
            {
                if (String.IsNullOrEmpty(firstNameTextBox.Text) && !String.IsNullOrEmpty(lastNameTextBox.Text))
                {
                    MessageBox.Show("Please include a first name or a date of birth to search for a patient.",
                        "Invalid search criteria", MessageBoxButton.OK, MessageBoxImage.Exclamation, MessageBoxResult.OK);
                }
                else if (String.IsNullOrEmpty(lastNameTextBox.Text) && !String.IsNullOrEmpty(firstNameTextBox.Text))
                {
                    MessageBox.Show("Please include a last name or a date of birth to search for a patient.",
                        "Invalid search criteria", MessageBoxButton.OK, MessageBoxImage.Exclamation, MessageBoxResult.OK);
                }
                else
                {
                    criteria.Add(firstNameTextBox.Text);
                    criteria.Add(lastNameTextBox.Text);
                }
            }
            else
            {
                if (String.IsNullOrEmpty(lastNameTextBox.Text))
                {
                    criteria.Add((DateTime.Parse(dobDatePicker.Text)).ToString("yyyy-MM-dd"));
                }
                else
                {
                    criteria.Add(lastNameTextBox.Text);
                    criteria.Add((DateTime.Parse(dobDatePicker.Text)).ToString("yyyy-MM-dd"));
                }
            }
            return criteria;
        }

        /*
         * Checks name inputs against a regular expression; if the input is valid, the method returns true and 
         * the program continues.  If input doesn't match the regex (contains a number in the name, for example), 
         * then the user is notified with a MessageBox, and the query is halted.
         */
        private bool IsValidInput()
        {
            if (!Regex.IsMatch(firstNameTextBox.Text, @"(^[a-zA-Z]{3,10}$)?") || !Regex.IsMatch(lastNameTextBox.Text, @"(^[a-zA-Z]{3,10}$)?"))
            {
                MessageBox.Show("A name must contain only alphabetic characters and be between 3 and 10 letters in length.",
                    "Invalid name", MessageBoxButton.OK, MessageBoxImage.Exclamation, MessageBoxResult.OK);
                return false;
            }

            if (dobDatePicker.Text != "")
            {
                DateTime selectedDate;
                if (!DateTime.TryParse(dobDatePicker.ToString(), out selectedDate))
                {
                    MessageBox.Show("The selected date is not recognized as a valid date.",
                        "Invalid date", MessageBoxButton.OK, MessageBoxImage.Exclamation, MessageBoxResult.OK);
                    return false;
                }
            }
            return true;
        }

        /*
         * If the user selects a date from the DataPicker, then there's no need to keep first name enabled
         */
        private void dobDatePicker_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
            firstNameTextBox.IsEnabled = false;
        }
    }
}
